<?php
/**
 * 简单的用户系统
 * 头像验证、用户组、实名认证
 * @author wolf
 * @since 2014-07-12
 *
 */
class MemberService implements IMember {
	
	const USERNAME = 'mobile_phone';
	// 系统默认管理员 权限从上到下 默认是5
	public $_group = array (1 => "站长", 2 => "管理员", 3 => "验证用户", 4 => "注册会员", 5 => "游客", 6 => "黑名单", 0 => "继承分类权限" );
	//分页数
	private $_num = 40;
	// 用来区分等级
	// 用户等级制度
	public $_verify = array ("-1" => "不通过", "0" => "尚未认证", "1" => "实名认证" );
	public $_status = array ("0" => "在职", "1" => "离职" );
	
	/**
	 * 返回用户组
	 * @return Array
	 */
	public function getGroup() {
		return MemberModel::instance ()->getGroupAll ();
	}
	
	/**
	 * 保存用户
	 */
	public function save($user) {
		
		if (! empty ( $user ['password'] )) {
			$salt = $this->randstr ();
			$data ['password'] = md5 ( md5 ( $user ['password'] ) . $salt );
			$data ['salt'] = $salt;
		}
	
		if (! empty ( $_FILES['face']['tmp_name'] )) {
			$data ['face'] = $this->upload ();
		}
		
		$data ['email'] = trim ( $user ['email'] );
		$data ['mobile_phone'] = trim ( $user ['mobile_phone'] );
		$data ['country'] = trim ( $user ['country'] );
		$data ['area'] = trim ( $user ['area'] );
		$data ['real_name'] = trim ( $user ['real_name'] );
		$data ['username'] = trim ( $user ['username'] );
		$data ['groupid'] = $user ['groupid'];
		$data ['verify'] = $user ['verify'];
		$data ['manager'] = $user ['manager'];
		$data ['status'] = $user ['status'];
		MemberModel::instance ()->setMemberByWhere ( $data, array ('uid' => $user ['uid'] ) );
		return self::SUCCESS;
	}
	
	/**
	 * 增加用户
	 */
	public function register($userInfo) {
		
		if (! $this->checkValidate ( $userInfo ['codeimg'] )) {
			return "验证码错误";
		}
		
		if (strlen ( $userInfo ['mobile_phone'] ) != 11) {
			return "手机号码为11位数";
		}
		
		if (strlen ( $userInfo ['password'] ) < 5) {
			return "密码至少为5位数";
		}
		
		if (strlen ( $userInfo ['username'] ) < 3) {
			return "用户名至少为3位数";
		}
		
		if ($this->filter ( $userInfo ['password'] )) {
			return "密码中包含了标点符号";
		}
		
		if ($this->filter ( $userInfo ['username'] )) {
			return "用户名中包含了标点符号";
		}
		
		if (! $this->checkRepeat ( 'mobile_phone', $userInfo ['mobile_phone'] )) {
			return "手机号码重复了!";
		}
		if (! $this->checkRepeat ( 'username', $userInfo ['username'] )) {
			return "帐号重复了!";
		}
		$this->addMember ( $userInfo );
		
		return self::SUCCESS;
	}
	
	/**
	 * 新增用户
	 * @param Array $userInfo
	 */
	private function addMember($userInfo) {
		$salt = $this->randstr ();
		$data ['username'] = trim ( $userInfo ['username'] );
		$data ['real_name'] = trim ( $userInfo ['real_name'] );
		$data ['password'] = md5 ( md5 ( $userInfo ['password'] ) . $salt );
		$data ['salt'] = $salt;
		$data ['add_time'] = time ();
		$ip = $this->getIp ();
		$data ['ip'] = $ip ['ip'];
		$data ['area'] = $ip ['country'] . $ip ['city'];
		$data ['mobile_phone'] = trim ( $userInfo ['mobile_phone'] );
		//防止非法修改
		$data ['groupid'] = trim ( $userInfo ['groupid'] ) > 10 ? trim ( $userInfo ['groupid'] ) : 10;
		$gremark = MemberModel::instance ()->getOneGroup ( array ('id' => $data ['groupid'] ) );
		$data ['remark'] = $gremark ['name'];
		$data ['verify'] = 0;
		//直接验证成功
		MemberModel::instance ()->addMember ( $data );
	}
	
	public function login($user) {
		if (! $this->checkValidate ( $user ['codeimg'] )) {
			return "验证码错误";
		}
		
		if ($this->filter ( $user ['password'] )) {
			return '密码中含有标点符号';
		}
		
		$userInfo = $this->isLogin ( $user ['mobile_phone'], $user ['password'] );
		//这里的$userInfo 返回一个对象 现在是数组
		if (! is_array ( $userInfo )) {
			return $userInfo;
		}
		//增加登录历史记录
		return self::SUCCESS;
	}
	
	/**
	 * 检测验证码是否正确
	 */
	private function checkValidate($codeimg) {
		if (! isset ( $codeimg )) {
			return false;
		}
		if (trim ( $codeimg ) != $_SESSION ["authnum_session"]) {
			return false;
		}
		return true;
	}
	
	public function getMemberGroup() {
		return MemberModel::instance ()->getGroupAll ();
	}
	//加密方法
	public function randstr($len = 6) {
		$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
		mt_srand ( ( double ) microtime () * 1000000 * getmypid () );
		$password = '';
		while ( strlen ( $password ) < $len ) {
			$password .= substr ( $chars, (mt_rand () % strlen ( $chars )), 1 );
		}
		return $password;
	}
	/**
	 * 检查用户是否重复
	 */
	public function checkRepeat($key, $value) {
		$rs = MemberModel::instance ()->getOneMember ( array ($key => trim ( $value ) ) );
		return empty ( $rs );
	}
	
	/**
	 * 获取用户信息
	 * @param int $uid
	 * @return Array
	 */
	public function getMemberByUid($uid) {
		return MemberModel::instance ()->getOneMember ( array ('uid' => $uid ) );
	}
	
	/**
	 * 判断是否登录
	 * @param String $username
	 * @param String $passsword
	 * @return Array 用户信息
	 */
	private function isLogin($username, $passsword) {
		
		//下面调用服务
		// 查询用户是否存在
		$userInfo = MemberModel::instance ()->getOneMember ( array ('mobile_phone' => $username ) );
		// 简单验证
		if (empty ( $userInfo )) {
			return "手机号码不存在";
		}
		if (strlen ( $username ) < 4 || strlen ( $passsword ) < 4) {
			return "用户名或密码不能小与6位!";
		}
		// 判断密码是否正确
		if ($userInfo ['password'] != md5 ( md5 ( $passsword ) . $userInfo ['salt'] )) {
			return "密码不正确";
		
		}
		//检查账号是否被禁用
		if ($userInfo ['status'] > 0) {
			return "账号已被禁用!";
		}
		
		return $userInfo;
	
	}
	
	/**
	 * 获取随机头像
	 * @param unknown_type $num
	 */
	public function getRandFace($num) {
		return MemberModel::instance ()->getRandFace ( $num );
	}
	/**
	 * 用户账户状态
	 * @param string $ids
	 * @param string $type
	 */
	public function saveStatus($ids, $type) {
		
		$data = substr ( trim ( $ids ), 1 );
		// 只复制一个的情况
		if (strpos ( $data, "," )) {
			$data = explode ( ",", $data );
			foreach ( $data as $v ) {
				if ($type == "refuse") {
					$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => - 1 ), array ('uid' => $v ) );
				}
				if ($type == "pass") {
					$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => 1 ), array ('uid' => $v ) );
				}
			}
		} else {
			if ($type == "refuse") {
				$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => - 1 ), array ('uid' => $data ) );
			}
			if ($type == "pass") {
				$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => 1 ), array ('uid' => $data ) );
			}
		}
		return self::SUCCESS;
	}
	
	/**
	 * 对接ckeditor
	 * 注意上传文件大小限制
	 *
	 * @return string $filePath 图片路径
	 */
	public function upload() {
		if (is_uploaded_file ( $_FILES ['face'] ['tmp_name'] )) {
			$upfile = $_FILES ['face'];
			$name = $upfile ['name'];
			$type = $upfile ['type'];
			$size = $upfile ['size'];
			$tmp_name = $upfile ['tmp_name'];
			$error = $upfile [error];
			switch ($type) {
				case 'image/jpeg' :
					$ok = 1;
					break;
				case 'image/pjpeg' :
					$ok = 1;
					break;
				case 'image/gif' :
					$ok = 1;
					break;
				case 'image/png' :
					$ok = 1;
					break;
				case 'image/x-png' :
					$ok = 1;
					break;
			}
			// 修正缩略图文件夹
			// 创建文件夹
			$save_path = getcwd () . "/static/attached/face/";
			$save_url = "./static/attached/face/";
			$ym = date ( "Ym" );
			$save_path .= $ym . "/";
			$save_url .= $ym . "/";
			if (! file_exists ( $save_path )) {
				mkdir ( $save_path );
			}
			if ($ok == '1' && $error == '0') {
				$fileType = substr ( $name, strpos ( $name, "." ) + 1 );
				$newName = time () . "." . $fileType;
				$filepath = $save_path . $newName;
				move_uploaded_file ( $tmp_name, $filepath );
				
				$callback = $_REQUEST ["CKEditorFuncNum"];
				//增加水印
				$this->thumb ( $filepath );
				return $save_url . $newName;
			} else {
				return self::ERROR;
			}
		}
	}
	
	/**
	 * 图片增加水印处理
	 * @param unknown_type $image
	 */
	private function thumb($image) {
		$imagetrans = new Image ();
		$imagetrans->watermark_logo = ROOT . "config/water.png";
		$imagetrans->originimage = $image;
		$imagetrans->thumb_maxheight = 500;
		$imagetrans->thumb_maxwidth = 500;
		//LOGO水印
		$imagetrans->gen_thumbimage ();
	}
	/**
	 * 获取ip
	 */
	protected function getIp() {
		$ip = new IpLocation ();
		$clientIp = $ip->getIP ();
		$rs = $ip->getlocation ( $clientIp );
		unset ( $rs ['beginip'] );
		unset ( $rs ['endip'] );
		foreach ( $rs as $k => $v ) {
			$v = iconv ( 'GB2312', 'UTF-8', $v );
			$arrIp [$k] = $v;
		}
		return $arrIp;
	}
	
	public function getOneMemberByUsername($username) {
		return MemberModel::instance ()->getOneMember ( array (self::USERNAME => $username ) );
	}
	
	/**
	 * 
	 * 搜索
	 */
	public function search($field, $value) {
		$rs = MemberModel::instance ()->getMemberByLike ( $field, $value );
		// 重组验证和等级
		foreach ( $rs as $k => $v ) {
			$rs [$k] ['verify'] = $this->_verify [$v ['verify']];
			$rs [$k] ['groupid'] = $this->_group [$v ['groupid']];
			$rs [$k] ['status'] = $this->_status [$v ['status']];
		
		}
		return $rs;
	}
	
	/**
	 * 删除会员 
	 * @param int $uid
	 */
	public function remove($uid) {
		
		if ($uid < 1) {
			return "id必须大于1";
		}
		
		$user = $this->getMemberByUid ( $uid );
		
		if (empty ( $user )) {
			return "用户不存在";
		}
		
		if (! empty ( $user ['coupons'] )) {
			return "用户积分还有剩余,无法删除";
		}
		
		MemberModel::instance ()->delMemberByWhere ( array ('uid' => $uid ) );
		return self::SUCCESS;
	}
	
	public function listing($currentPage, $data) {
		$where = null;
		
		$group = $this->getGroup ();
		//系统组别
		$groupname = array (0 => "All" );
		foreach ( $group as $v ) {
			$groupname [$v ['id']] = $v ['name'];
		}
		foreach ( $data as $k => $v ) {
			if (! empty ( $v ) && $k != "p" && $k != "mb") {
				$where [$k] = $v;
			}
		}
		$totalNum = MemberModel::instance ()->countMember ( $where );
		$page = $this->page ( $currentPage, $totalNum );
		$memberlist = MemberModel::instance ()->getPages ( $page ['start'], $page ['num'], $where, "uid DESC" );
		// 重组验证和等级
		foreach ( $memberlist as $k => $v ) {
			$memberlist [$k] ['verify'] = $this->_verify [$v ['verify']];
			$memberlist [$k] ['groupid'] = $this->_group [$v ['groupid']];
			$memberlist [$k] ['status'] = $this->_status [$v ['status']];
		
		}
		return array ('totalnum' => $totalNum, 'memberlist' => $memberlist, 'groupname' => $groupname, 'verify' => $this->_verify, 'page' => $page );
	}
	
	/**
	 * 设置图 并且设置等级为1
	 * Enter description here ...
	 * @param unknown_type $v
	 * @param unknown_type $where
	 */
	public function saveFace($path, $uid, $level = 0) {
		return MemberModel::instance ()->setMemberByWhere ( array ('face' => $path, 'level' => $level ), array ('uid' => $uid ) );
	}
	
	/**
	 * 用户修改密码
	 * @param int $uid
	 * @param String $password
	 * @param String $newPassword
	 */
	public function rePasswordByUser($uid, $password, $newPassword) {
		$user = MemberModel::instance ()->getOneMember ( array ('uid' => trim ( $uid ) ) );
		$oldPassword = md5 ( md5 ( $password ) . $user ['salt'] );
		
		if ($this->filter ( $newPassword )) {
			return "密码中请勿包含标点符号等";
		}
		
		if ($newPassword == $password) {
			return "新的密码和旧密码不能相同";
		}
		
		if (strlen ( $newPassword ) < 5) {
			return "密码至少为6位";
		}
		
		if ($user ['password'] != $oldPassword) {
			return "原密码错误";
		} else {
			$this->rePasssword ( $uid, trim ( $newPassword ) );
			return "修改成功,下次登录时生效";
		}
	}
	
	/**
	 * 检测是否包含非法字符
	 * @return boolean true or false
	 */
	private function filter($str) {
		$pattern = "#[\*\.\/\?\-\%\!]+#i";
		return preg_match ( $pattern, $str );
	}
	
	/**
	 * 分页
	 *
	 * @return void
	 */
	protected function page($p, $total) {
		
		$pageid = isset ( $p ) ? $p : 1;
		$start = ($pageid - 1) * $this->_num;
		$pagenum = ceil ( $total / $this->_num );
		return array ('start' => $start, 'num' => $this->_num, 'current' => $pageid, 'page' => $pagenum );
	
	}
}